/*
Version: MPL 1.1/GPL 2.0/LGPL 2.1

The contents of this file are subject to the Mozilla Public License Version 
1.1 (the "License"); you may not use this file except in compliance with 
the License. You may obtain a copy of the License at 
http://www.mozilla.org/MPL/

Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the
License.

The Original Code is jsLex - JavaScript profiling injection engine.

The Initial Developer of the Original Code is
Robert Buffone.
Portions created by the Initial Developer are Copyright (C) 2007
the Initial Developer. All Rights Reserved.

Contributor(s):

Robert Buffone

Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL.
*/

package com.nexaweb.jslex.ant;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.text.DecimalFormat;
import java.util.Enumeration;
import java.util.Set;
import java.util.Vector;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.filters.util.ChainReaderHelper;
import org.apache.tools.ant.taskdefs.Copy;
import org.apache.tools.ant.types.FilterSet;
import org.apache.tools.ant.types.FilterSetCollection;
import org.apache.tools.ant.util.LineTokenizer;

import com.nexaweb.jslex.classloader.ScriptClassLoader;

/**
 * Class handles the compression of the code and the injection
 * of profiling information via an ant task.
 * 
 * attributes that can be set:
 * toDir - the directory where the compressed files will be placed.
 * profilingMode - none, counters, timing, callGraph, ifAnalysis
 * sourceDir - The location of the files to compress.
 * endOfLine - none, safe, all
 * verbose - true, false default is true.
 *  
 * @author bbuffone
 *
 */
public class JsLexCompInject extends Copy {
	
    //-----------------------------------------------------------------------
    // Constants.
    //-----------------------------------------------------------------------

	private static final int BUF_SIZE = 8192;
	private final static DecimalFormat 	PRECENT_DECIMAL_FORMAT = new DecimalFormat("#.##");
	private final static String			END_OF_LINE = "\r\n";
	private final static String			DEFAULT_JSLEX_PATH = "jsLex-script.jar";

	// -----------------------------
	// class variables
	// -----------------------------
	private File	_profilingFile = null;

	private String	_profilingMode = null;
	private String	_endOfLine = null;
	private String	_compressNames = null;
	private String  _jsLexScriptPath = DEFAULT_JSLEX_PATH;
	
	private long	_numberOfFiles = 0;
	private long	_totalSize = 0;
	private long 	_totalCompressedSize = 0;
	private long 	_compressionErrors = 0;
	
	private StringBuffer	_profilingFileContents = new StringBuffer(60000);	
	private ScriptClassLoader _scriptClassLoader = null;
	
	
	// -----------------------------------
	// methods
	// -----------------------------------

	/**
	 * Initialize the class loaded then create the JsLexUtil class that the ant task
	 * will interface with.
	 * 
	 * @throws BuildException
	 */
	public void createJsLexUtil() throws BuildException {
		try {
			_scriptClassLoader = 
					ScriptClassLoader.getInstance(getClass().getClassLoader(), 
												_jsLexScriptPath);
		} catch (MalformedURLException malformedURLException) {
			throw new BuildException(malformedURLException);
		}
	}
	
    //-----------------------------------------------------------------------
    // Overrides From CopyTask.
    //-----------------------------------------------------------------------

	/**
	 * Called to actually execute the build task.
	 */
	public void execute() throws BuildException {
		
		//create the util class for jsLex.
		createJsLexUtil();
				
		_profilingFileContents.append("<analysis>" + END_OF_LINE);
		super.execute();		
		_profilingFileContents.append("</analysis>" + END_OF_LINE);
		
		//save the profile file to disk.
		saveProfileFile();

		//output totals
		String 	precent = PRECENT_DECIMAL_FORMAT.format(100.0 - ((double)_totalCompressedSize / (double)_totalSize) * 100.0 );
		log(END_OF_LINE, verbosity);
		log("jsLex Task Summary", verbosity);
		log("----------------- ", verbosity);
		log("---Total files: " + _numberOfFiles, verbosity);
		if (_compressionErrors != 0){
			log("---Compression errors: " + _compressionErrors, verbosity);
		}
		log("---Total pre-comressed size: " + _totalSize, verbosity);
		log("---Total compressed size: " + _totalCompressedSize, verbosity);
		log("---Compression ratio: " + precent, verbosity);
	}
	
    /**
     * Actually does the file (and possibly empty directory) copies.
     * This is a good method for subclasses to override.
     */
    protected void doFileOperations() {
        if (fileCopyMap.size() > 0) {
            log("Compressing " + fileCopyMap.size()
                + " file" + (fileCopyMap.size() == 1 ? "" : "s")
                + " to " + destDir.getAbsolutePath());

            Enumeration e = fileCopyMap.keys();
            while (e.hasMoreElements()) {
                String fromFile = (String) e.nextElement();
                String[] toFiles = (String[]) fileCopyMap.get(fromFile);

                for (int i = 0; i < toFiles.length; i++) {
                    String toFile = toFiles[i];

                    if (fromFile.equals(toFile)) {
                        log("Skipping self-compressing of " + fromFile, verbosity);
                        continue;
                    }

                    try {
                        log("Compressing " + fromFile + " to " + toFile, verbosity);

                        FilterSetCollection executionFilters =
                            new FilterSetCollection();
                        if (filtering) {
                            executionFilters
                                .addFilterSet(getProject().getGlobalFilterSet());
                        }
                        for (Enumeration filterEnum = getFilterSets().elements();
                            filterEnum.hasMoreElements();) {
                            executionFilters
                                .addFilterSet((FilterSet) filterEnum.nextElement());
                        }
                        
                        //need to compress the current file.
                        try{
                        	File	fromFileFile = new File(fromFile);
                        	String content = compressFile(fromFileFile, getEndOfLine(), getProfilingMode(), getCompressNames());
                        	
                        	//keep track of the sizes and the compression size.
        					if (content != null){
                            	copyFile(content, new File(toFile), executionFilters,
                                        getFilterChains(), forceOverwrite,
                                        preserveLastModified, getEncoding(),
                                        getOutputEncoding(), getProject());

                            	long	size = fromFileFile.length();
        						_profilingFileContents.append("<file fullPath=\"" + fromFile.replace("\\", "/") + "\" name=\"" + fromFileFile.getName() + "\" size=\"" + size + "\">" + END_OF_LINE);	
        						
        						String 	precent = PRECENT_DECIMAL_FORMAT.format(100.0 - ((double)content.length() / (double)size) * 100.0 );
        						_profilingFileContents.append("<info compressedSize=\"" + content.length() + "\" compressionRatio=\"" + precent + "\">" + END_OF_LINE);
        						
        						//add all the function information 
        						addFunctionInfo();
        						
        						_profilingFileContents.append("</info>" + END_OF_LINE);
        						_profilingFileContents.append("</file>" + END_OF_LINE);

        						_numberOfFiles++;
        						_totalSize += size;
        						_totalCompressedSize += content.length();
        					}else{
        						_compressionErrors++;
        					}
        					
                        }catch(BuildException buildException){}
                        
                        
                    } catch (IOException ioe) {
                        String msg = "Failed to compress " + fromFile + " to " + toFile
                            + " due to " + ioe.getMessage();
                        File targetFile = new File(toFile);
                        if (targetFile.exists() && !targetFile.delete()) {
                            msg += " and I couldn't delete the corrupt " + toFile;
                        }
                        throw new BuildException(msg, ioe, getLocation());
                    }
                }
            }
        }

        if (includeEmpty) {
            Enumeration e = dirCopyMap.elements();
            int createCount = 0;
            while (e.hasMoreElements()) {
                String[] dirs = (String[]) e.nextElement();
                for (int i = 0; i < dirs.length; i++) {
                    File d = new File(dirs[i]);
                    if (!d.exists()) {
                        if (!d.mkdirs()) {
                            log("Unable to create directory "
                                + d.getAbsolutePath(), Project.MSG_ERR);
                        } else {
                            createCount++;
                        }
                    }
                }
            }
            if (createCount > 0) {
                log("Compressed " + dirCopyMap.size()
                    + " empty director"
                    + (dirCopyMap.size() == 1 ? "y" : "ies")
                    + " to " + createCount
                    + " empty director"
                    + (createCount == 1 ? "y" : "ies") + " under "
                    + destDir.getAbsolutePath());
            }
        }
    }

    //-----------------------------------------------------------------------
    // Public Methods.
    //-----------------------------------------------------------------------

    public String getTaskName() {
		return "jsLex";
	}
	
	public String getDescription() {
		return "jsLex allows developers to inject profiling code inside their JavaScript application to track function counters, time and call graph information.";
	}

	public void setProfilingFile(File profilingFile){
		_profilingFile = profilingFile;
		log("Attribute supplied - profilingFile = " + profilingFile, verbosity);
	}
		
	public void setProfilingMode(String profilingMode){
		_profilingMode = profilingMode;
		log("Attribute supplied - profilingMode = " + profilingMode, verbosity);
	}
	
	public void setEndOfLine(String endOfLine){
		_endOfLine = endOfLine;
		log("Attribute supplied - endOfLine = " + endOfLine, verbosity);
	}
	
	public void setJsLexScriptPath(String jsLexScriptPath){
		_jsLexScriptPath = jsLexScriptPath;
		log("Attribute supplied - jsLexScriptPath = " + jsLexScriptPath, verbosity);
	}

	public void setCompressNames(String compressNames){
		_compressNames = compressNames;
		log("Attribute supplied - compressNames = " + compressNames, verbosity);
	}

    //-----------------------------------------------------------------------
    // Private Methods.
    //-----------------------------------------------------------------------

	/**
	 * Get endOfLine setting, throw exception if it is not valid;
	 * @return
	 * @throws BuildException
	 */
	private int getEndOfLine() throws BuildException{
		if (_endOfLine == null){
			throw new BuildException("Invalid endOfLine setting for jsLex task, setting = " + _endOfLine);
		}else if (_endOfLine.equals("none") == true){
			return 0;
		}else if (_endOfLine.equals("safe") == true){
			return 1;			
		}else if (_endOfLine.equals("all") == true){		
			return 2;
		}else{
			throw new BuildException("Invalid endOfLine setting for jsLex task, setting = " + _endOfLine);
		}
	}
	
	/**
	 * Get the profiling mode as an exception.
	 * @return
	 * @throws BuildException
	 */
	private int getProfilingMode() throws BuildException{
		if (_profilingMode == null){
			throw new BuildException("Invalid profilingMode setting for jsLex task, setting = " + _profilingMode);
		}else if (_profilingMode.equals("none") == true){
			return 0;
		}else if (_profilingMode.equals("count") == true){
			return 1;			
		}else if (_profilingMode.equals("timing") == true){		
			return 2;
		}else if (_profilingMode.equals("callGraph") == true){		
			return 3;
		}else if (_profilingMode.equals("ifAnalysis") == true){		
			return 4;
		}else{
			throw new BuildException("Invalid profilingMode setting for jsLex task, setting = " + _profilingMode);
		}
	}
	
	private int getCompressNames() throws BuildException{
		if (_compressNames == null){
			throw new BuildException("Invalid compressNames setting for jsLex task, setting = " + _compressNames);
		}else if (_compressNames.equals("none") == true){
			return 0;
		}else if (_compressNames.equals("normal") == true){
			return 1;			
		}else{
			throw new BuildException("Invalid profilingMode setting for jsLex task, setting = " + _compressNames);
		}
	}
		
	private File getProfilingFile() throws BuildException{
		if (_profilingFile == null){
			throw new BuildException("Invalid profilingFile setting for jsLex task, setting = " + _profilingFile);
		}else if (_profilingFile.exists() == true && _profilingFile.isFile() == false){
			throw new BuildException("Invalid profilingFile setting for jsLex task, setting = " + _profilingFile + " is not a file.");
		}
		return _profilingFile;
	}
	
    /**
     * Add the function to index mapping to the info object
     * @param info
     */
    private void addFunctionInfo(){
		Object[] keyArray;
		Set keys = _scriptClassLoader.getCounterFunctionKeys();
		keyArray = keys.toArray();
		
		//freeze updated to the UI
		for (int index = 0; index < keys.size(); index++){
			Integer	profileIndex = (Integer)keyArray[index];
			String	functionName = (String)_scriptClassLoader.getFunctionName(profileIndex);

			_profilingFileContents.append("<function index=\"" + 
						profileIndex.toString() + "\" name=\"" + functionName + "\"/>" + END_OF_LINE);		    
		}

		_scriptClassLoader.clearCounterFunctionKeys();
    }
    
	/**
     * Compress the file content using the Dojo compression
     * 
     * @param fileContent
     * @return
     */
    private String compressFile(File sourceFile, int eol, int profileInjectionValue, int compressNames) throws BuildException{
    	try{
    		return _scriptClassLoader.compressFile(sourceFile, eol, profileInjectionValue, compressNames);
    	}catch (IOException ioException){
    		System.err.println("Compression error ( " + sourceFile.getAbsolutePath() + " )");
			throw new BuildException(ioException);
    	}catch (Exception exception){
    		System.err.println("Compression error ( " + sourceFile.getAbsolutePath() + " )");
			throw new BuildException(exception);
    	}
    }
       

	/**
	 * Save the profile file that was created to disk.
	 *
	 */
	private void saveProfileFile() {
		try {
			FileWriter		fileWriter = new FileWriter(getProfilingFile());
			fileWriter.write(_profilingFileContents.toString());
			fileWriter.close();
		} catch (FileNotFoundException fileNotFoundException) {
			fileNotFoundException.printStackTrace();
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}

    /**
     * Convenience method to copy a file from a source to a
     * destination specifying if token filtering must be used, if
     * filter chains must be used, if source files may overwrite
     * newer destination files and the last modified time of
     * <code>destFile</code> file should be made equal
     * to the last modified time of <code>sourceFile</code>.
     *
     * @param sourceFile the file to copy from.
     *                   Must not be <code>null</code>.
     * @param destFile the file to copy to.
     *                 Must not be <code>null</code>.
     * @param filters the collection of filters to apply to this copy.
     * @param filterChains filterChains to apply during the copy.
     * @param overwrite Whether or not the destination file should be
     *                  overwritten if it already exists.
     * @param preserveLastModified Whether or not the last modified time of
     *                             the resulting file should be set to that
     *                             of the source file.
     * @param inputEncoding the encoding used to read the files.
     * @param outputEncoding the encoding used to write the files.
     * @param project the project instance.
     *
     *
     * @throws IOException if the copying fails.
     *
     */
    private void copyFile(String content, File destFile,
                         FilterSetCollection filters, Vector filterChains,
                         boolean overwrite, boolean preserveLastModified,
                         String inputEncoding, String outputEncoding,
                         Project project)
        throws IOException {

        if (overwrite || !destFile.exists()) {

            if (destFile.exists() && destFile.isFile()) {
                destFile.delete();
            }
            // ensure that parent dir of dest file exists!
            // not using getParentFile method to stay 1.1 compat
            File parent = destFile.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }
            final boolean filterSetsAvailable = (filters != null
                                                 && filters.hasFilters());
            final boolean filterChainsAvailable = (filterChains != null
                                                   && filterChains.size() > 0);
            if (filterSetsAvailable) {
                BufferedReader in = null;
                BufferedWriter out = null;
                try {
                    in = new BufferedReader(new StringReader(content));
                    if (outputEncoding == null) {
                        out = new BufferedWriter(new FileWriter(destFile));
                    } else {
                        OutputStreamWriter osw
                            = new OutputStreamWriter(new FileOutputStream(destFile),
                                                     outputEncoding);
                        out = new BufferedWriter(osw);
                    }
                    if (filterChainsAvailable) {
                        ChainReaderHelper crh = new ChainReaderHelper();
                        crh.setBufferSize(BUF_SIZE);
                        crh.setPrimaryReader(in);
                        crh.setFilterChains(filterChains);
                        crh.setProject(project);
                        Reader rdr = crh.getAssembledReader();
                        in = new BufferedReader(rdr);
                    }
                    LineTokenizer lineTokenizer = new LineTokenizer();
                    lineTokenizer.setIncludeDelims(true);
                    String newline = null;
                    String line = lineTokenizer.getToken(in);
                    while (line != null) {
                        if (line.length() == 0) {
                            // this should not happen, because the lines are
                            // returned with the end of line delimiter
                            out.newLine();
                        } else {
                            newline = filters.replaceTokens(line);
                            out.write(newline);
                        }
                        line = lineTokenizer.getToken(in);
                    }
                } finally {
                	if (out != null) out.close();
                	if (in != null) in.close();
                }
            } else if (filterChainsAvailable
                       || (inputEncoding != null
                           && !inputEncoding.equals(outputEncoding))
                       || (inputEncoding == null && outputEncoding != null)) {
                BufferedReader in = null;
                BufferedWriter out = null;
                 try {
                     in = new BufferedReader(new StringReader(content));
                     if (outputEncoding == null) {
                         out = new BufferedWriter(new FileWriter(destFile));
                     } else {
                         out =
                             new BufferedWriter(
                                 new OutputStreamWriter(
                                     new FileOutputStream(destFile),
                                     outputEncoding));
                     }
                     if (filterChainsAvailable) {
                         ChainReaderHelper crh = new ChainReaderHelper();
                         crh.setBufferSize(BUF_SIZE);
                         crh.setPrimaryReader(in);
                         crh.setFilterChains(filterChains);
                         crh.setProject(project);
                         Reader rdr = crh.getAssembledReader();
                         in = new BufferedReader(rdr);
                     }
                     char[] buffer = new char[BUF_SIZE];
                     while (true) {
                         int nRead = in.read(buffer, 0, buffer.length);
                         if (nRead == -1) {
                             break;
                         }
                         out.write(buffer, 0, nRead);
                      }
                 } finally {
                 	if (out != null) out.close();
                	if (in != null) in.close();
                 }
            } else {
            	ByteArrayInputStream in = null;
                FileOutputStream out = null;
                try {
                    in = new ByteArrayInputStream(content.getBytes());
                    out = new FileOutputStream(destFile);

                    byte[] buffer = new byte[BUF_SIZE];
                    int count = 0;
                    do {
                        out.write(buffer, 0, count);
                        count = in.read(buffer, 0, buffer.length);
                    } while (count != -1);
                } finally {
                	if (out != null) out.close();
                	if (in != null) in.close();
                }
            }
        }
    }

}
